package com.lanou.tipsy.fragment.search;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou.tipsy.R;
import com.lanou.tipsy.adapter.search.HotSearchAdapter;
import com.lanou.tipsy.adapter.search.SearchInfoAdapter;
import com.lanou.tipsy.base.Constants;
import com.lanou.tipsy.entity.search.AlbumEntity;
import com.lanou.tipsy.entity.search.hot.HotSearchResultEntity;
import com.lanou.tipsy.adapter.search.SearchAdapter;
import com.lanou.tipsy.base.BaseFragment;
import com.lanou.tipsy.entity.search.hot.HotSearch;
import com.lanou.tipsy.entity.search.SearchSongEntity;
import com.lanou.tipsy.entity.search.SongSearch;
import com.lanou.tipsy.fragment.main.MainFragment;
import com.lanou.tipsy.tools.formatCodeUtil.FormatCodeUtil;
import com.lanou.tipsy.tools.volley.VolleySingleton;

import org.json.JSONObject;

import java.util.ArrayList;


/**
 * Created by ws on 15/10/20.
 * 搜索
 */
public class SearchFragment extends BaseFragment implements View.OnClickListener {

    private FragmentManager manager;
    private ImageView songSearchBackIV;// 界面返回按钮
    private EditText searchETv; //搜索输入框
    private ImageButton searchIBtn;//搜索按按钮
    private ArrayList<SearchSongEntity> data; //实体类
    private SearchAdapter adapter; //适配器
    private RequestQueue queue;//队列
    private ListView songSearchLV; //列表布局
    Handler myhandler = new Handler();
    private ImageView ivDeleteText; //删除按钮
    private LinearLayout hotSearchLayout;       //声明热门搜索布局
    private HotSearchAdapter hotSearchAdapter;//声明热门搜索适配器
    //热门搜索网址链接
    private static String hotSearchUrl = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.search.hot";
    private GridView songSearchGv;//热门搜索gridview
    private ArrayList<HotSearchResultEntity> hotSearchResultEntity;//接受数据实体类
    private VolleySingleton volleySingleton;
    private LinearLayout searchClickLayout;//声明搜索行布局
    private SearchInfoAdapter searchInfoAdapter;
    private ArrayList<AlbumEntity> albumEntities;  //列表接受实体类
    private ImageView searchInIv;//
    private TextView searchInNameTv;
    private TextView searchInSingerTv;
    private ImageLoader imageLoader;
    private ListView searchLv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fr_search, null);

        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init(getView());

    }

    private void init(View v) {
        songSearchLV = (ListView) v.findViewById(R.id.songSearchLV);
        //绑定布局
        songSearchBackIV = (ImageView) v.findViewById(R.id.songSearchBackIV);
        searchETv = (EditText) v.findViewById(R.id.searchETv);
        searchIBtn = (ImageButton) v.findViewById(R.id.searchIBtn);
        hotSearchLayout = (LinearLayout) v.findViewById(R.id.hotSearchLayout);
        songSearchGv = (GridView) v.findViewById(R.id.songSearchGv);
        searchETv = (EditText) v.findViewById(R.id.searchETv);
        searchInIv = (ImageView) v.findViewById(R.id.searchInIv);
        searchInNameTv = (TextView) v.findViewById(R.id.searchInNameTv);
        searchInSingerTv = (TextView) v.findViewById(R.id.searchInSingerTv);
        searchClickLayout = (LinearLayout) v.findViewById(R.id.searchClickLayout);
        searchLv = (ListView) v.findViewById(R.id.searchLv);

        //绑定监听
        songSearchBackIV.setOnClickListener(this);
        searchIBtn.setOnClickListener(this);
        //初始化
        volleySingleton = VolleySingleton.getInstance();
        //热门搜索网络数据解析
        JsonObjectRequest jr = new JsonObjectRequest(hotSearchUrl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                String st = response.toString();
                HotSearch hotSearch = JSON.parseObject(st, HotSearch.class);
                hotSearchResultEntity = hotSearch.getResult();
                hotSearchAdapter = new HotSearchAdapter(getContext(), hotSearchResultEntity);
                songSearchGv.setAdapter(hotSearchAdapter);
                songSearchGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                         String s = hotSearchResultEntity.get(position).getWord().toString();
                        searchETv.setText(s);

                    }
                });

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        //添加队列
        volleySingleton.addQueue(jr);


        //数据变化调取的方法
        set_eSearch_TextChanged(getView());
        //数据出现时候点击删除的方法
        set_ivDeleteText_OnClick(getView());
    }

    //数据变化的方法
    private void set_eSearch_TextChanged(View v) {

        //数据改变的监听
        searchETv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // //这个应该是在改变的时候会做的动作
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //这是文本框改变之前会执行的动作
            }

            @Override
            public void afterTextChanged(Editable s) {
                /***
                 * 这是文本框改变之后 会执行的动作
                 * 因为我们要做的就是 ,  在文本框改变的同时,我们的listview的数据也相应的变动
                 * 并且如一的显示在界面上
                 * 所以这里我们就需要加上数据的修改的动作了
                 */
                if (s.length() == 0) {
                    //删除数据按钮
                    ivDeleteText.setVisibility(View.GONE);
                    //热门搜索按钮
                    hotSearchLayout.setVisibility(View.VISIBLE);
                    searchClickLayout.setVisibility(View.GONE);
                } else {
                    ivDeleteText.setVisibility(View.VISIBLE);
                    hotSearchLayout.setVisibility(View.GONE);
                }
                //post线程
                myhandler.post(eChanged);

            }
        });
    }

    /****
     * 利用线程实现UI界面更新
     */
    Runnable eChanged = new Runnable() {
        @Override
        public void run() {
            //从searchETv组件获得数据
            String datas = searchETv.getText().toString();
            //将searchETv获得数据转化成utf-8格式数据
            String songUrl = FormatCodeUtil.codingFormat(datas);
            //进行网址拼接
            String url = Constants.SEARCH_URL + songUrl;
            //进行网络请求
            StringRequest sr = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    //进行Gson数据解析
                    Gson gson = new Gson();
                    final SongSearch songSearch = gson.fromJson(response, SongSearch.class);
                    //获得数据
                    data = songSearch.getSong();
                    //初始化适配器
                    adapter = new SearchAdapter(getActivity(), data);
                    //绑定适配器
                    songSearchLV.setAdapter(adapter);
                    //添加行布局监听
                    songSearchLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            String title = songSearch.getSong().get(position).getSongname();
                            String singer = songSearch.getSong().get(position).getArtistname();
                            searchETv.setText(title + "-" + singer);

                        }
                    });

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            //添加队列
            volleySingleton.addQueue(sr);
        }

    };


    private void set_ivDeleteText_OnClick(View v) {
        ivDeleteText = (ImageView) v.findViewById(R.id.ivDeleteText);
        ivDeleteText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                //将数据滞空
                searchETv.setText("");

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.searchIBtn:
                //得到数值
                String type = searchETv.getText().toString();
                if (type == null || type == "") {
                    Toast.makeText(getContext(), "内容不能为空", Toast.LENGTH_SHORT).show();
                } else if (type != null && type != "") {
                    //出现具体布局
                    searchClickLayout.setVisibility(View.VISIBLE);
                    //热门搜索布局消失
                    hotSearchLayout.setVisibility(View.GONE);
                    //歌曲搜索列表消失
                    songSearchLV.setVisibility(View.GONE);

                    String name = FormatCodeUtil.codingFormat(type);

                    String getUrl = Constants.SEARCH_URL + name;
                    volleySingleton = VolleySingleton.getInstance();
                    StringRequest srs = new StringRequest(getUrl, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {

                            Gson gson = new Gson();
                            SongSearch songSearch = gson.fromJson(response, SongSearch.class);
                            data = songSearch.getSong();
                            albumEntities = songSearch.getAlbum();
                            searchInfoAdapter = new SearchInfoAdapter(getContext(), data);
                            searchLv.setAdapter(searchInfoAdapter);

                            imageLoader = volleySingleton.getImageLoader();
                            if (albumEntities != null && albumEntities.size() > 0) {
                                String url = albumEntities.get(0).getAlbumname();
                                if (url != null && url != "") {
                                    ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(searchInIv,
                                            R.mipmap.logo_2, R.mipmap.error);
                                    imageLoader.get(url, imageListener);
                                }
                                searchInNameTv.setText(albumEntities.get(0).getAlbumname());
                                searchInSingerTv.setText(albumEntities.get(0).getArtistname());
                            }
                            //搜索界面行布局窗口弹出监听
                            searchLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                                }
                            });
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {


                        }
                    });
                    volleySingleton.addQueue(srs);
                }
                break;

            case R.id.songSearchBackIV:
                manager = getFragmentManager();
                MainFragment mainFragment = new MainFragment();
                getFragmentManager().beginTransaction().replace(R.id.fl_main, mainFragment).commit();

                break;
        }
    }
}